using System;
using QAssetBundle;
using UnityEngine;
using QFramework;
using Random = UnityEngine.Random;

namespace QFramework.Monk
{
	public partial class Ball : ViewController
	{
		private SimpleBall mOwer;
		private Camera mCamera;
		
		

		public Ball WithOwner(SimpleBall owner)
		{
			mOwer = owner;
			return this;
		}
		
		private void Awake()
		{
			mCamera = Camera.main;
			SelfRigidbody2D.velocity = new Vector2(Random.Range(-10,10), Random.Range(-10,10)).normalized*mOwer.Speed;
			
			HitBox.OnTriggerEnter2DEvent(collider2D =>
			{
				if (collider2D.gameObject.layer == LayerMask.NameToLayer("Enemy"))
				{
					var enemy = collider2D.GetComponentInParent<EnemyBase>();
					if (enemy!=null)
					{
						var dir = (enemy.Position()-Player.Default.Position()).normalized;
						enemy.HitBack(dir*mOwer.HitBackFactor);
						enemy.CostHp(AppStart.damage.Value);
					}
				}
				
			}).UnRegisterWhenGameObjectDestroyed(this.gameObject);
		}

		private void OnCollisionEnter2D(Collision2D other)
		{
			//获取碰撞对象的法线
			var  normal = other.contacts[0].normal;
			if (normal.x>normal.y)//横向
			{
				//给法线y添加随机值
				normal = new Vector3(normal.x,Mathf.Sign(normal.y)*Random.Range(0.5f,2f)).normalized;
					
			}
			else//纵向
			{
				normal = new Vector3(Mathf.Sign(normal.x)*Random.Range(0.5f,2f),normal.y).normalized;
			}

			AudioKit.PlaySound(Sxf.BALL);
			SelfRigidbody2D.velocity = normal*mOwer.Speed;
			SelfRigidbody2D.angularVelocity = Random.Range(-360f,360f);	
		}

		private void Update()
		{
			transform.Rotate(Vector3.forward,Time.deltaTime*360);
			// 获取物体在屏幕上的位置
			Vector3 screenPos = mCamera.WorldToViewportPoint(transform.position);

			// 判断物体是否超出屏幕范围
			/*if (screenPos.x < 0 || screenPos.x > 1 || screenPos.y < 0 || screenPos.y > 1 || screenPos.z < 0)
			{
				this.DestroySelfGracefully();
			}*/
			
		}
	}
}
